<template>
  <div id="addProducts">
    <!-- 表格 -->
    <div class="table">
      <!-- 表格名称 -->
      <div class="sTitle homeTitle">
        <span>质押品管理</span>
        <el-input placeholder="搜索债券代码" v-show="isbond" v-model="code" class="input-with-select">
          <el-button slot="append" @click="getBondList" icon="el-icon-search"></el-button>
        </el-input>
      </div>
      <!-- 表格 -->
     
      <div class="tablecon">

          <el-table :data="tableData" border style="width: 100%" v-if="isbond">
            <el-table-column prop="code" label="债券代码" align="center"></el-table-column>
            <el-table-column prop="name" label="债券全称" align="center"></el-table-column>
            <el-table-column prop="simple" label="债券简称" align="center"></el-table-column>
            <el-table-column prop="nature" label="债券性质" align="center"></el-table-column>
            <el-table-column prop="mainUnderwrite" label="主承销商" align="center"></el-table-column>
            <el-table-column prop="mechanismName" label="发行机构名称" align="center"></el-table-column>
            <el-table-column prop="subject" label="主体评级" align="center"></el-table-column>
            <el-table-column prop="debt" label="债项评级" align="center"></el-table-column>
            <el-table-column prop="address" label="操作" align="center" width="172">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="selected(scope.row)">选中</el-button>
              </template>
            </el-table-column>
        </el-table>
        <el-table :data="tableData" v-else border style="width: 100%">
          <el-table-column prop="code" label="债券代码"  align="center"></el-table-column>
          <el-table-column prop="fullName" label="债券全称"  align="center"></el-table-column>
          <el-table-column prop="variety" label="债券品种"  align="center"></el-table-column>
          
          <el-table-column prop="holdPosition" label="可用持仓(万元)" align="center"></el-table-column>
          <el-table-column prop="settlementDate" label="结算日期" align="center"></el-table-column>
          <el-table-column prop="yield" label="到期收益率(%)" align="center"></el-table-column>
          <el-table-column prop="netWorth" label="买入净价(元/百元面额)" align="center"></el-table-column>
          <el-table-column prop="fullPrice" label="买入全价(元/百元面额)" align="center"></el-table-column>
          <el-table-column prop="transactionNumber" label="交易编号"  align="center"></el-table-column>
          <el-table-column prop="holdPledgeThawed" label="质押式正回购待解冻（万元）"  align="center"></el-table-column>
          <el-table-column prop="holdOutThawed" label="买断式正回购待解冻（万元）"  align="center"></el-table-column>
          <el-table-column prop="applyPledgeThawed" label="申请中质押式正回购待解冻（万元）"  align="center"></el-table-column>
          <el-table-column prop="applyOutThawed" label="申请中买断式正回购待解冻（万元）"  align="center"></el-table-column>
          <el-table-column prop="applyRRThawed" label="申请中融入待解冻（万元）"  align="center"></el-table-column>
          <el-table-column prop="holdRRThawed" label="持有融入待解冻（万元）"  align="center"></el-table-column>
           <el-table-column prop="applyRCThawed" label="申请中融出待解冻（万元）"  align="center"></el-table-column>
          <el-table-column prop="holdRCThawed" label="持有融出待解冻（万元）"  align="center"></el-table-column>
          <el-table-column prop="address" label="操作" align="center" width="172">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="selected(scope.row)">{{scope.row.btntext}}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <div class="pgfy">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="10"
          layout="total, prev, pager, next, jumper"
          :total="totalpage">
        </el-pagination>
      </div>
      <!-- -------第二个表格------------- -->
       <div class="tablecon second">
         <div class="secondTitle">已选定质押品：</div>
        <el-table :data="selectedData" border style="width: 100%">
          <el-table-column prop="code" label="债券代码"  align="center"></el-table-column>
          <el-table-column prop="fullName" label="债券全称"  align="center"></el-table-column>
          <el-table-column prop="simpleName" label="债券简称"  align="center"></el-table-column>
          <el-table-column prop="variety" label="债券品种"  align="center"></el-table-column>
          <el-table-column prop="sumMoney" label="质押券面总额(万元)"  align="center">
             <template slot-scope="scope">
              <el-input v-if="scope.row.isEdit" type="text" v-model="scope.row.sumMoney"></el-input>
              <span v-else>{{scope.row.sumMoney}}</span>
            </template>
            
          </el-table-column>
          <el-table-column prop="ratio" label="折算比例(%)"  v-show="!isjd" align="center">
             <template slot-scope="scope">
              <el-input v-if="scope.row.isEdit" type="text" v-model="scope.row.ratio"></el-input>
              <span v-else>{{scope.row.ratio}}</span>
            </template>
            
          </el-table-column>
          <el-table-column prop="settlementAmount" v-show="!isjd" label="结算金额(万元)"  align="center">
             <template slot-scope="scope">
              <el-input v-if="scope.row.isEdit" type="text" v-model="scope.row.settlementAmount"></el-input>
              <span v-else>{{scope.row.settlementAmount}}</span>
            </template>
            
          </el-table-column>
          <el-table-column prop="address" label="操作" align="center" width="172">
            <template slot-scope="scope">
              <el-button size="mini" @click="editMoney(scope.row)" type="text">{{scope.row.btntext}}</el-button>
              <el-button size="mini" @click="cancle(scope.row)" type="text">取消选定</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="btns" style="text-align:center">
    <el-button type="primary"  @click="complete">完成</el-button>
    <el-button type="primary"  @click="goback">取消</el-button>
    </div>

  </div>
</template>

<script>
export default {
  name: 'sellingDebts',
  data () {
    return {
      search: '',
      isEdit:false,
      isjd: false, // 是否为借贷
      btntext: '调整质押面额',
      tableData: [],
      selectedData: [],
      code:'',
      isbond: false,
      tableList: [
        {label: '交易类型', prop: ''},{label: '交易编号', prop: ''},{label: '剩余面额(万元)', prop: ''},{label: '结算日期', prop: ''},
        {label: '买入净价(元/百元面额)', prop: ''},{label: '买入全价(元/百元面额)', prop: ''},{label: '交易类型', prop: ''},
        {label: '应计利息(元/百元面额)', prop: ''}
      ],
      // 分页
      currentPage: 1,
      totalpage: 0
    };
  },
  mounted() {
    if(this.$route.query.direction == '正回购' || this.$route.query.direction == '融入') {
      this.isbond = false
      this.getList()
    }
    if(this.$route.query.direction == '逆回购' || this.$route.query.direction == '融出') {
      this.isbond = true
      this.getBondList()
    }
    if(sessionStorage.getItem('pledata')) {
      let data = JSON.parse(sessionStorage.getItem('pledata')) 
      data.forEach((item, index) => {
        // item.btntext = '调整面额'
        // item.index = index
        // item.isEdit = false
        // item.beforeMoney = 0   这种会导致不可编辑
        let rows = {...item, index: this.selectedData.length, btntext: '调整质押面额', isEdit: false, beforeMoney: 0, bondType: item.type,
        bhId: item.bondRepurchaseId}  //等价上面？？  扩展
        this.selectedData.push(rows)
        
      })
    }
  },
  methods: {
     getBondList() {
      let data = {}
      data.code = this.code
      data.page = this.currentPage
      
        this.axios.get('bond/selectList', {
            params: data
        }).then((res) => {
           let data = res.data.data
          data.forEach((item) => {
            item.btntext = '选定'
            item.fullName = item.name
            item.simpleName = item.simple
            item.variety = item.nature
          })
           this.tableData = data
           this.totalpage = res.data.pageInfo.total
           if(sessionStorage.getItem('pledata')) {
        
            let index = this.getIndex(this.tableData, this.selectedData)
            console.log(index)
            this.tableData[index].btntext = '已选定'
          }
        })
    },
     // 分页
    handleSizeChange(val) {
    },
    // 分页
    handleCurrentChange(val) {
      this.currentPage = val
  
      if(this.$route.query.direction == '正回购') {
     // this.isbond = false
      this.getList()
    }
    if(this.$route.query.direction == '逆回购') {
      //this.isbond = true
      this.getBondList()
    }
     if(this.$route.query.direction == '融入') {
      this.isjd = true
      this.getList()
    }
    if(this.$route.query.direction == '融出') {
      this.isjd = true
      this.getBondList()
    }
    },
    getList() {
      let data = {
        page: this.currentPage,
        limit: 5
      }
      this.axios.get('pledge/findAllByBank', {params: data}).then(res => {
      
        let data = res.data.data
          data.forEach((item) => {
            item.btntext = '选定'
          })
        this.tableData = data
        this.totalpage = res.data.pageInfo.total
        if(sessionStorage.getItem('pledata')) {
       
          let index = this.getIndex(this.tableData, this.selectedData)
          console.log(index)
          this.tableData[index].btntext = '已选定'
        }
      })
    },
    getIndex(top, bot) {
     
      for(let i = 0; i < top.length; i++) {
        for(let j = 0; j < bot.length; j++) {
          if(top[i].bhId == bot[j].bondRepurchaseId) {
            return i
          }
        }
      }
    },
    editMoney(row) {
      if(row.isEdit) {
        row.btntext = '调整质押面额'
         row.remainingMoney = Number(row.remainingMoney) +  Number(row.beforeMoney) - Number(row.sellMoney)
        row.beforeMoney = row.sellMoney
        row.isEdit =false
        
      }else {
        row.btntext = '确认调整'
        row.isEdit = true
      }
    
    },
    selected(row) {
      if(row.btntext == '选定') {
        row.btntext = '已选定'
    //    let {...rows} = row //解构赋值 深拷贝
        let rows = {...row, index: this.selectedData.length,bhId: row.bhId, btntext: '调整质押面额', isEdit: false, beforeMoney: 0}  //等价上面？？  扩展
        this.selectedData.push(rows)
      } else {
        this.$message({
          type: 'warning',
          message: '已选定，不可再选'
        })
      }
      
    },
    cancle(row) {
        //取消选定
        this.selectedData.forEach((item, index) => {
            if(row.index == index)
              this.selectedData.splice(index, 1)
        })
        this.tableData.forEach((item, index) => {
          if(item.id == row.id) {
            item.btntext = '选定'
          }
        })
    },
    goback() {
      this.$router.go(-1)
    },
    complete() {
      
      let param = []
      let data = this.selectedData
      let len = data.length
      for(let i = 0; i < len; i++) {
        console.log(data[i].sumMoney)
         if(data[i].sumMoney == undefined || data[i].ratio == undefined || data[i].settlementAmount == undefined) {
            this.$message({
              type:'warning',
              message: '质押品信息填写不完整'
            })
            return
          }
          if(data[i].sumMoney == '' || data[i].ratio == '' || data[i].settlementAmount == '') {
            this.$message({
              type:'warning',
              message: '质押品信息填写不完整'
            })
            return
          }
      }
      debugger
      this.selectedData.forEach(item => {
       
        let obj = {
          id: item.id,
          type: item.bondType,
          bondRepurchaseId: item.bhId,
          bondId: item.bId,
          code: item.code,
          fullName: item.fullName,
          simpleName: item.simpleName,
          variety: item.variety,
          sumMoney: item.sumMoney
          
        }
        if(!this.isjd) {
          obj.ratio = item.ratio,
          obj.settlementAmount = item.settlementAmount
        }
        param.push(obj)
      })

      
      let params = {
        direction: this.$route.query.direction,
        pledges: param
      }
      this.axios.post('pledge/add', params).then(res => {
        sessionStorage.setItem('strdata', res.data.data)
        this.$router.go(-1)
      })
      
     
    }
  }
};
</script>

<style lang="scss">
.el-pagination button, .el-pagination span:not([class*=suffix]){
  color: white;
}
  #addProducts {
     // ------表格------
    .table {
      .el-input__inner{
        color:white;
        border: 1px solid white;
        background: transparent
      }
      .sTitle {
        height: 50px;
        line-height: 50px;
        padding-left: 20px;
        // border-bottom: 1px solid #000;
        display: flex;
        align-items: center;
        justify-content: space-between;
        
        .el-input {
          width: 400px;
          margin-right: 20px;
        }
      }
      .tablecon {
        padding: 21px;
        // background: white;
        margin-top: 30px;
        &.second {
          margin-top: 0;
          .secondTitle {
            margin-bottom: 20px;
            margin-bottom: 20px;
            color: white;
          }
        }
      }
      .pgfy {
        padding: 20px;
        padding-top: 10px;
        text-align: right;
        // background: white;
      }
    }
  }
</style>
